﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace JinYuan.Models.HelperAttribute
{
    public static class AnnotationUtils
    {
        public static List<PropertyInfo> GetPropertiesWithAnnotation<T>(Type type) where T : Attribute
        {
            var properties = type.GetProperties().Where(p => p.GetCustomAttributes(typeof(T), true).Length > 0).ToList();
            return properties;
        }

        /// <summary>
        /// 获取当前类的DataGridViewColumn
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static List<DataGridViewColumn> GetDataGridViewColumns(this object obj)
        {
            Type typeObj = obj.GetType();
            var properties = AnnotationUtils.GetPropertiesWithAnnotation<DataGridViewColumn>(typeObj);

            List<DataGridViewColumn> list = new List<DataGridViewColumn>();
            foreach (var property in properties)
            {
                DataGridViewColumn attribute = property.GetCustomAttribute<DataGridViewColumn>();
                //数据源名称
                attribute.DataPropertyName = property.Name;
                list.Add(attribute);
            }

            return list;
        }

    }
}
